package com.zjdiepu.www.rest.api.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.ParentModel;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.AttachmentLabel;
import com.zjdiepu.www.base.enums.type.AttachmentType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.commpent.handler.TokenUserHelper;
import com.zjdiepu.www.commpent.mapper.base.OtherAttachmentsVoMapper;
import com.zjdiepu.www.ibiz.base.IOtherAttachmentsService;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.OtherAttachmentsExt;
import com.zjdiepu.www.model.base.request.AttachmentsRequest;
import com.zjdiepu.www.model.base.response.AttachmentsResponse;
import com.zjdiepu.www.util.CachedEnums;

/**
 * 附件信息Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月03日 11时48分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "OtherAttachmentsController", produces="application/json;charset=UTF-8", method = RequestMethod.POST)
@Api(tags = {"附件信息"}, produces="application/json;charset=UTF-8")
public class OtherAttachmentsController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(OtherAttachmentsController.class);
	
    @Resource
    private IOtherAttachmentsService otherAttachmentsService;
    @Resource
    private OtherAttachmentsVoMapper otherAttachmentsVoMapper;
    @Resource
    private IQiniuFileService qiniuFileService;
    @Resource
	private TokenUserHelper tokenUserHelper;

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增附件信息 <br/>
     * @param otherAttachments
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增附件信息", response = OtherAttachments.class, httpMethod="POST")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @RequestMapping(value = "save")
    public ApiResponse save(@Validated(Add.class) @RequestBody OtherAttachments otherAttachments) {
    	SysUser currentUser = tokenUserHelper.getUser();
    	otherAttachments.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	otherAttachments.setModifierName(currentUser.getName());
        otherAttachmentsService.saveUpdateAndDelete(otherAttachments, OperateType.add, null);
        //打水印
        qiniuFileService.imagesWater(otherAttachments.getOssPath(), otherAttachments.getId());
        otherAttachmentsVoMapper.mapper(otherAttachments);
        return ApiResponse.success(otherAttachments);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: attachmentsList  <br/>
     * @Description: 附件列表 <br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "附件列表", response = AttachmentsResponse.class, httpMethod="POST")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @RequestMapping(value = "attachmentsList", method = RequestMethod.POST)
    public ApiResponse attachmentsList(@Validated @RequestBody AttachmentsRequest attachmentsRequest) {
    	tokenUserHelper.getUser();
    	OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
    	otherAttachmentsExt.setBaseWhere();
    	otherAttachmentsExt.withOutPage();
    	otherAttachmentsExt.setDpStatus(1);
    	otherAttachmentsExt.setDataid(attachmentsRequest.getDataid());
    	otherAttachmentsExt.setSubDataid(attachmentsRequest.getSubDataid());
    	otherAttachmentsExt.setAttachmentSort(attachmentsRequest.getAttachmentSort());
    	otherAttachmentsExt.setFileLabel(attachmentsRequest.getAttachmentLabel());
    	otherAttachmentsExt.setOrderSql("`FILE_LABEL`");
    	
    	List<OtherAttachments> otherAttachmentss = otherAttachmentsService.selectByExt(otherAttachmentsExt);
    	List<AttachmentsResponse> attachmentsResponses = mapOtherAttachmentss(otherAttachmentss);
        return ApiResponse.success(attachmentsResponses);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除附件信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除附件信息", response = Boolean.class, httpMethod="POST")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @RequestMapping("remove")
    public ApiResponse remove(@Validated @RequestBody ParentModel parentModel) {
    	SysUser currentUser = tokenUserHelper.getUser();
    	List<String> ids = Arrays.asList(parentModel.getId().split(","));
    	otherAttachmentsService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
//  ============================================辅助方法===========================================
    
  /**
   * 转换属性：展示
   * @param otherAttachments
   * @return
   */
  private List<AttachmentsResponse> mapOtherAttachmentss(List<OtherAttachments> otherAttachments){
	  if(CollectionUtils.isEmpty(otherAttachments)) {
	  		return CollectionInitUtil.emptyList();
	  	}
	  	List<AttachmentsResponse> attachmentsResponses = CollectionInitUtil.emptyList();
	  	for(OtherAttachments otherAttachment : otherAttachments) {
	  		AttachmentsResponse attachmentsResponse = mapOtherAttachments(otherAttachment);
	  		if(attachmentsResponse != null) {
	  			attachmentsResponses.add(attachmentsResponse);
	  		}
	  	}
	  	return attachmentsResponses;
  }
  
  /**
   * 转换属性：展示
   * @param otherAttachment
   * @return
   */
  private AttachmentsResponse mapOtherAttachments(OtherAttachments otherAttachment){
  	if(otherAttachment == null) {
  		return null;
  	}
  	try {
		AttachmentsResponse attachmentsResponse = new AttachmentsResponse();
		BeanUtils.copyProperties(attachmentsResponse, otherAttachment);
		String customLabelName = attachmentsResponse.getCustomLabelName();
		if(StringUtils.isBlank(customLabelName)) {
			String fileLabel = attachmentsResponse.getFileLabel();
			attachmentsResponse.setCustomLabelName((String)CachedEnums.getValue(fileLabel, AttachmentLabel.class));
		}
		String ossPath = attachmentsResponse.getOssPath();
		if(StringUtils.isNotBlank(ossPath)) { //获取授权地址
			if(AttachmentType.IMAGE.getCode().equals(attachmentsResponse.getAttachmentType())){ //缩略图
    			String url = qiniuFileService.getURL(ossPath + SystemConsts.THUMBNAIL_SUBBFIX);
    			attachmentsResponse.setUrl(url);
			}
			
			String bigUrl = qiniuFileService.getURL(ossPath); //原图
			attachmentsResponse.setBigUrl(bigUrl);
		}
		return attachmentsResponse;
	} catch (IllegalAccessException | InvocationTargetException e) {
		logger.error("对象拷贝属性出错.", e);
		return null;
	}
  }
}
